export const isNumber = str => Number(str) ? true : false

const getNumberIsC = (i, arr) => {
  let newArr = getNumber(i, arr)
  let result = 0
  for (let j = 0; j < newArr.length; j++) {
    if (newArr[j] === 'C') {
      newArr = getNumber(j, newArr)
    }
  }
  for (let j = 0; j < newArr.length; j++) {
    const element = getNumber(j, newArr);
    result += element
  }
  return result
}

export const getFraction = arr => {
  let result = 0
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 'C') {
      return getNumberIsC(i, arr)
    }

    result += getNumber(i, arr)
  }
  return result
}

export const getNumber = (index, arr) => {
  if (isNumber(arr[index])) {
    return Number(arr[index])
  }
  if (arr[index] === 'D') {
    return getNumber(index - 1, arr) * 2
  }
  if (arr[index] === '+') {
    let result = 0
    const first = index -2 >= 0 ? index - 2: 0
    for (let i = first;i < index; i++) {
      const value = getNumber(i, arr)
      result += value
    }
    return result
  }
  if (arr[index] === 'C') {
    arr.splice(index - 1, 2)
    return arr
  }
}

